﻿import 'package:azring/pages/action/routes.dart';
import 'package:azring/pages/action/stress_relief/routes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'actionState.dart';
import '../../routes/app_routes.dart';
import '../../core/repository/default_api.dart';
import '../../core/models/action_record.dart';
import '../../core/models/health_plan.dart';

/// 行动页控制器
class ActionLogic extends GetxController {
  /// 状态实例
  final ActionState state = ActionState();

  /// API实例
  final DefaultApi _api = DefaultApi();

  @override
  void onInit() {
    super.onInit();
    _loadActions();
    _loadActionTypes();
    _loadRelaxTypes(); // 加载减压助眠类型
    _loadHealthPlans();

    // 监听筛选条件变化，重新加载健康计划
    ever(state.planFilter, (_) => _loadHealthPlans());
  }

  /// 加载行动类型（从字典获取）
  Future<void> _loadActionTypes() async {
    try {
      state.isLoadingActionTypes.value = true;

      const String dictType = 'az_action_type';

      final response = await _api.dataTypeGet<List<dynamic>>(
        dictType: dictType,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (response != null) {
        state.actionTypes.assignAll(
          response.map((item) => item as Map<String, dynamic>).toList(),
        );
      } else {
        state.actionTypes.clear();
      }
    } catch (e) {
      print('加载行动类型失败: $e');
      state.actionTypes.clear();
    } finally {
      state.isLoadingActionTypes.value = false;
    }
  }

  /// 加载减压助眠类型（从字典获取）
  Future<void> _loadRelaxTypes() async {
    try {
      state.isLoadingRelaxTypes.value = true;

      const String dictType = 'az_relax_type';

      final response = await _api.dataTypeGet<Map<String, dynamic>>(
        dictType: dictType,
        isShowErrMsg: false,
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        final List<dynamic> data = response['data'] ?? [];
        state.relaxTypes.assignAll(
          data.map((item) => item as Map<String, dynamic>).toList(),
        );
        print('加载减压助眠类型成功: ${state.relaxTypes.length} 条');
      } else {
        state.relaxTypes.clear();
      }
    } catch (e) {
      print('加载减压助眠类型失败: $e');
      state.relaxTypes.clear();
    } finally {
      state.isLoadingRelaxTypes.value = false;
    }
  }

  @override
  void onReady() {
    super.onReady();
    // 页面准备完成后的逻辑
  }

  @override
  void onClose() {
    super.onClose();
    // 清理资源
  }

  /// 加载行动计划
  void _loadActions() {
    state.actions.assignAll([
      {'title': '早起运动', 'completed': false, 'time': '07:00'},
      {'title': '冥想练习', 'completed': true, 'time': '08:30'},
      {'title': '健康饮食', 'completed': false, 'time': '12:00'},
      {'title': '晚间阅读', 'completed': false, 'time': '21:00'},
    ]);
  }

  /// 切换行动完成状态
  void toggleAction(int index) {
    final action = state.actions[index];
    action['completed'] = !(action['completed'] as bool);
    state.actions[index] = action;
    state.actions.refresh();
  }

  /// 添加新行动
  void addAction(String title, String time) {
    state.actions.add({
      'title': title,
      'completed': false,
      'time': time,
    });
  }

  /// 打开减压冥想
  void openGoalTracking() {
    // 查找减压类型的 dictValue
    final stressReliefType = state.relaxTypes.firstWhereOrNull(
      (type) => type['dictLabel']?.toString().contains('减压') ?? false,
    );
    
    final relaxTypeValue = stressReliefType?['dictValue'] ?? 'stress_relief';
    print('打开减压页面，relaxType: $relaxTypeValue');
    
    Get.toNamed(
      StressReliefRoutes.stressRelief,
      arguments: {'relaxType': relaxTypeValue},
    );
  }

  /// 打开助眠页面
  void openHabitBuilding() {
    // 查找助眠类型的 dictValue
    final sleepAidType = state.relaxTypes.firstWhereOrNull(
      (type) => type['dictLabel']?.toString().contains('助眠') ?? false,
    );
    
    final relaxTypeValue = sleepAidType?['dictValue'] ?? 'sleep_aid';
    print('打开助眠页面，relaxType: $relaxTypeValue');
    
    Get.toNamed(
      StressReliefRoutes.sleepAid,
      arguments: {'relaxType': relaxTypeValue},
    );
  }

  /// 打开行动类别
  /// [dictValue] 字典值（actionType）
  /// [dictLabel] 字典标签
  Future<void> openActionCategory(String dictValue, String dictLabel) async {
    print('打开行动类别: $dictLabel (actionType: $dictValue)');

    try {
      // 调用接口获取该类型的行动记录列表
      final response = await _api.getActionRecordListGet<List<dynamic>>(
        actionType: dictValue,
        isShowErrMsg: true,
        isShowLoading: true,
      );

      if (response != null && response.isNotEmpty) {
        final records = response
            .map((json) => ActionRecord.fromJson(json as Map<String, dynamic>))
            .toList();
        print('获取到 ${records.length} 条行动记录');

        // 导航到课程列表页面
        Get.toNamed(
          '/course-list',
          arguments: {
            'title': dictLabel,
            'courses': records,
          },
        );
      } else {
        Toast.show('暂无${dictLabel}课程');
      }
    } catch (e) {
      print('获取行动记录失败: $e');
      Toast.show('获取行动记录失败');
    }
  }

  /// 显示课程介绍弹窗
  void _showCourseModal(Map<String, String> course) {
    Get.bottomSheet(
      Container(
        height: Get.height * 0.85,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
        ),
        child: Column(
          children: [
            // 顶部图片区域
            Stack(
              children: [
                Container(
                  height: 300.h,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    borderRadius:
                        BorderRadius.vertical(top: Radius.circular(20.r)),
                    image: DecorationImage(
                      image:
                          AssetImage('assets/images/mindful_breathing_bg.jpg'),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius:
                          BorderRadius.vertical(top: Radius.circular(20.r)),
                      gradient: LinearGradient(
                        begin: Alignment.topCenter,
                        end: Alignment.bottomCenter,
                        colors: [
                          Colors.transparent,
                          Colors.black.withOpacity(0.3),
                        ],
                      ),
                    ),
                  ),
                ),
                // 关闭按钮
                Positioned(
                  top: 16.h,
                  right: 16.w,
                  child: GestureDetector(
                    onTap: () => Get.back(),
                    child: Container(
                      padding: EdgeInsets.all(8.w),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.8),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.close,
                        color: Colors.grey[600],
                        size: 20.sp,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            // 内容区域
            Expanded(
              child: Padding(
                padding: EdgeInsets.all(20.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(
                          Icons.headphones,
                          color: Colors.orange,
                          size: 20.sp,
                        ),
                        SizedBox(width: 8.w),
                        Text(
                          course['duration']!,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: Colors.orange,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      course['title']!,
                      style: TextStyle(
                        fontSize: 24.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: 16.h),
                    Text(
                      course['description']!,
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.grey[600],
                        height: 1.5,
                      ),
                    ),
                    SizedBox(height: 24.h),
                    Text(
                      '冥想技巧',
                      style: TextStyle(
                        fontSize: 18.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: 12.h),
                    Text(
                      course['techniques']!,
                      style: TextStyle(
                        fontSize: 15.sp,
                        color: Colors.grey[600],
                        height: 1.5,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            // 底部开始按钮
            Padding(
              padding: EdgeInsets.all(20.w),
              child: SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: () {
                    Get.back(); // 关闭弹窗
                    _startAudioSession(course);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    padding: EdgeInsets.symmetric(vertical: 16.h),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(30.r),
                    ),
                    elevation: 3,
                  ),
                  child: Text(
                    '开始',
                    style: TextStyle(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
    );
  }

  /// 开始音频会话
  void _startAudioSession(Map<String, String> course) {
    // Get.toNamed(AppRoutes.audioPlayer, arguments: course);
  }

  /// 加载健康计划列表
  Future<void> _loadHealthPlans() async {
    try {
      state.isLoadingHealthPlans.value = true;

      // 获取设备SN，这里需要根据实际情况获取

      // 根据筛选条件设置planStatus参数
      String? planStatus;
      switch (state.planFilter.value) {
        case '进行中':
          planStatus = '1';
          break;
        case '已生成':
          planStatus = '2';
          break;
        case '已完成':
          planStatus = '3';
          break;
      }

      final response = await _api.queryHealthPlanListGet<List<dynamic>>(
        planStatus: planStatus,
        isShowErrMsg: true,
        isShowLoading: false,
      );

      if (response != null) {
        final plans = response
            .map((json) => HealthPlan.fromJson(json as Map<String, dynamic>))
            .toList();
        state.healthPlans.assignAll(plans);
      } else {
        state.healthPlans.clear();
      }
    } catch (e) {
      print('加载健康计划失败: $e');
      Toast.show(
        '加载失败',
      );
    } finally {
      state.isLoadingHealthPlans.value = false;
    }
  }

  /// 刷新健康计划
  Future<void> refreshHealthPlans() async {
    await _loadHealthPlans();
  }

  /// 领取积分
  Future<void> claimPoints(HealthPlan plan) async {
    try {
      final response = await _api.claimPointsPost(
        id: plan.id!,
        planPoints: plan.planPoints ?? 0,
        isShowErrMsg: true,
        isShowLoading: true,
      );

      if (response != null) {
        Toast.show(
          '积分领取成功！',
        );
        // 刷新健康计划列表
        await _loadHealthPlans();
      }
    } catch (e) {
      print('领取积分失败: $e');
      Toast.show(
        '积分领取失败: $e',
      );
    }
  }
}
